<?php

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                               |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: xiangminghu@clcw.com.cn                                        |
// +------------------------------------------------------------------------+
//

namespace AuctionBack\Controller;

use AuctionCore\CarResource\Car;
use AuctionCore\Account\Back\Employee;
use AuctionCore\CarResource\CarList as CarList;
use AuctionCore\System\AuctionException;
use AuctionCore\Common\Page;
use AuctionCore\CarResource\SelfReceiveCar;
use AuctionCore\PurchaseOrder\PurchaseOrder;
use AuctionCore\Cashier\Collection;
use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\CarResource\BreachCar;
use AuctionCore\ChangeOrder\ChangeOrder;

/**
 * 车辆查询
 * @author Xmh
 */
class CarCheckController extends BaseController
{

    public function __construct()
    {
        parent::__construct();
        //页面头部信息
        $head = C('HEAD_INDEX');
        $this->assign("web_title", $head['title']);
        $this->assign("web_keywords", $head['keywords']);
        $this->assign("web_description", $head['description']);
        $this->emp_id = $this->user_info['emp_id'];
        //模板赋值
        $this->assign("emp_id", $this->emp_id);

        $order_pay_status = C('ORDER_PAY_STATUS');
        unset($order_pay_status[0]);
        $this->assign('order_pay_status', $order_pay_status);
    }

    /**
     * 车辆查询列表
     */
    public function index()
    {
        //获取父级渠道来源
        $pfrom = M("come_from")->where("pid=-2 AND is_delete=0")->select();
        //获取渠道来源列表
        $cols = 'a.from_id,a.from_name,b.from_name AS pname,b.from_id AS pid,b.sort AS psort';
        $condition['a.pid'] = array('neq', '-2');
        $condition['a.is_delete'] = array('eq', '0');
//        $condition['a.from_id'] = array('neq', '-1');
        $order = 'psort ASC,from_id ASC,pid DESC';
        $from = M("come_from")->alias('a')
            ->join('INNER JOIN (SELECT from_id,from_name,sort FROM au_come_from WHERE pid=-2 AND is_delete=0) AS b ON a.pid=b.from_id')
            ->field($cols)
            ->where($condition)
            ->order($order)
            ->select();
        $this->assign('from', $from);
        $this->assign('pfrom', $pfrom);

        $checker_auth_id = C('APPRAISER')[0];
        $checkers = \AuctionCore\Account\Back\Employee::get_emp_by_group_or_store($checker_auth_id);
        $this->assign("checker", $checkers);


        $branch_id = $this->user_info['branch_id'];
        //分公司列表
        $bc_list = $this->get_branch_company_list();
        $this->assign('bc_list', $bc_list);
        $this->assign('branch_id', $branch_id);


        $comefrom_list = $this->get_comefrom_list();
        //城市对应的4s店
        $bc_city = $this->bc_city;
        $city_fours_list = array();
        foreach ($bc_city as $kb => $vb) {
            $city_fours = M("come_from")->alias('a')->field('a.from_id,a.from_name')
                ->join(C('DB_PREFIX') . 'fours as f ON a.from_id = f.channel_id')
                ->where(array('f.city' => $kb))
                ->order('from_id ASC,pid DESC')
                ->select();
            $city_fours_list[$kb] = $city_fours;
        }
        $this->assign('comefrom_list', $comefrom_list);
        $this->assign('city_fours_list', $city_fours_list);
        $this->display();
    }

    /**
     * 车辆查询列表数据
     */
    public function car_list()
    {
        $page = I("get.p", 1);
        $size = 10;
        $params = array();
        $params['start_time'] = I('get.start_time');
        $params['end_time'] = I('get.end_time');
        $params['car_status'] = I('get.car_status/d');              //车辆状态
        $params['pay_status'] = I('get.pay_status/d');              //付款状态
        $params['location_area'] = I('get.location_area');          //车辆所在地
        $params['comefrom'] = I('get.comefrom', -2);                //车辆来源
        $params['car_no'] = I('get.car_no');                        //车辆编号
        $params['car_level'] = I('get.car_level');                  //车辆等级
        $params['car_plate_number'] = I('get.car_plate_number');    //车牌号
        //$params['car_vin'] = I('get.car_vin');                    //车架号
        $params['checker_id'] = I('get.checker_id');                //评估师
        $params['emp_id'] = $this->emp_id;
        //所在地查询
        if (count($this->bc_city) > 1) {
            $bc_code = array_flip($this->bc_city);
            $bc_code = implode(',', $bc_code);
            $params['bc_city'] = $bc_code;
        }
        //获取list
        $cl = new CarList();
        $result = $cl->get_car_list($page, $size, $params);
        $list = empty($result['list']) ? array() : $result['list'];
        //分页
        $Page = new \AuctionCore\Common\AjaxPage($result['total'], $size, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %nextPage% %downPage%  %end% %jumpform%");
//        dump($list);
        $show = $Page->show();          // 分页显示输出
        $this->assign('page', $show);   // 赋值分页输出
        $this->assign('list', $list);
        $this->assign('p', $page);

        $show_from = $this->get_from();  //获取渠道来源信息
        $this->assign('show_from', $show_from);
        $this->display();
    }


    /**
     * 车辆详情
     */
    public function car_info()
    {
        $sid = I('get.id/d');
        if ($sid) {
            $carData = Car::getValidCarIdBySid($sid); //根据sid得到有效的车辆编号
            $carArr = [];
            foreach ($carData as $key => $value) {
                $carArr[] = $value['car_id'];
            }
            //$carArr = $carData;
            $car_id = $carArr[0];
            //车辆信息
//            $car = M('cars')->where(array('car_id' => $car_id))->find();
            $car = M('cars')->alias('c')->field('c.*,co.comefrom,co.comefrom_url')
                ->join(C('DB_PREFIX') . "car_owner as co ON c.`owner_id`=co.`owner_id`")
                ->where(array('car_id' => $car_id))->find();
            $cm = new \AuctionCore\CarResource\CarModel();
            $brand = $cm->get_model_by_id($car['brand_id'], 'brand');
            $series = $cm->get_model_by_id($car['series_id'], 'series');
            $model = $cm->get_model_by_id($car['model_id']);
            $model_show = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
            $car_info['car_id'] = $car['car_id'];
            $car_info['sno'] = $car['sno'];
            $car_info['car_no'] = $car['car_no'];
            $car_info['car_status'] = $car['car_status'];
            $car_info['model'] = $model_show ? $model_show : $car['car_model'];
            $car_info['mession'] = C('EMISSION.' . $car['emission']);
            $car_info['first_reg_date'] = date("Y年m月d日", strtotime($car['first_reg_date']));
            $car_info['color'] = C('CAR_COLOR.' . $car['car_color']);
            $car_info['pointer_mileage'] = sprintf("%.2f", $car['pointer_mileage'] / 10000) . "万公里"; //round($car['pointer_mileage']/10000,2).'万公里';
            $car_info['car_level'] = $car['composite_state'] . $car['accident_level'];
            $a = new \AuctionCore\Other\Address();
            $area = $a->get_province($car['reg_city']);
            $province = $area['province'];
            $city = $area['city_name'];

            $location_area = $a->get_name_by_code($car['location_area']);
            $car_info['location_area'] = $location_area;

            if ($car['is_re_check']) { //如果是重新检测
                $car_info['car_status'] = 10;
            } else {
                $car_info['car_status'] = $car['car_status'];
            }
            $car_info['reg_city'] = $province . " " . $city;
            $car_info['car_plate_number'] = C('PLATE_PREFIX.' . $car['plate_prefix']) . $car['plate_suffix'];
            $car_info['car_vin'] = $car['vin'];
            $car_info['suggest_max_price'] = format_money($car['suggest_max_price']);
            $car_info['suggest_min_price'] = format_money($car['suggest_min_price']);
            $car_info['transfer_limit'] = $car['transfer_limit'];
            $car_info['comefrom'] = $car['comefrom'];
            $car_info['comefrom_url'] = $car['comefrom_url'];
            $owner = M('car_owner')->field('seller_name,phone,owner_type,contact_person')
                ->where(array('owner_id' => $car['owner_id']))
                ->find();
            $owner['owner_type_name'] = C('OWNER_TYPE_NAME')[$owner['owner_type']];
            $order = M('order')->alias('o')
                ->join(C('DB_PREFIX') . "order_scene as os ON o.scene_id=os.scene_id")
                ->where(array('o.car_id' => ['in', $carArr]))
                ->select();
            // print_r(M()->getLastSql());
            $order_list = array();
            foreach ($order as $ko => $vo) {
                $order_list[$ko]['is_other_channel_deal'] = $vo['is_other_channel_deal'];//是否其他渠道成交
                $order_list[$ko]['order_no'] = $vo['order_no'];
                $order_list[$ko]['car_id'] = $vo['car_id'];
                if ($order_list[$ko]['is_other_channel_deal'] == 1) { //如果是其他渠道成交
                    $isSelfReceive = $car['is_self_receive'];
                    $orderId = $vo['order_id'];
                    $map['order_id'] = $orderId;
                    $map['payment_type'] = 1; //1 应收车款
                    $auorderObj = new AuOrder($orderId);
                    $collectionOrderInfo = $auorderObj->getCollectionOrderRelationByCondition($map);

                    $colletionId = $collectionOrderInfo['collection_id'];
                    $collectionInfo = Collection::getInfoById($colletionId);

                    $sid = $car['sid'];
                    $purchaseOrderObj = new PurchaseOrder();
                    $purchaseOrderData = $purchaseOrderObj->viewBySid($sid);

                    if ($isSelfReceive == 1) { //如果是自收车辆
                        $selfObj = new SelfReceiveCar();
                        $selfCarData = $selfObj->getInfoByOtherOrderId($orderId);
                        $order_list[$ko]['order_amount'] = $selfCarData['trade_price']; //订单金额
                        $order_list[$ko]['transfer_fee'] = $selfCarData['transfer_fee']; // 交易佣金
                        $order_list[$ko]['modify_no'] = ''; //变更单号
                        $order_list[$ko]['purchase_order_nu'] = $purchaseOrderData['purchase_order_nu']; //采购单编号
                        $order_list[$ko]['create_time'] = $vo['create_time']; //订单生成时间
                        $order_list[$ko]['collection_no'] = $collectionInfo['collection_no'];
                    } else {
                        $breachCarInfo = BreachCar::getInfoByOtherOrderId($orderId);
                        $order_list[$ko]['order_amount'] = $breachCarInfo['trade_price']; //订单金额
                        $order_list[$ko]['transfer_fee'] = $breachCarInfo['transfer_fee']; // 交易佣金
                        $mid = $breachCarInfo['mid'];
                        $changeOrderInfo = ChangeOrder::getOneInfo($mid);
                        $order_list[$ko]['modify_no'] = $changeOrderInfo['modify_no']; //变更单号
                        $order_list[$ko]['purchase_order_nu'] = $purchaseOrderData['purchase_order_nu']; //采购单编号
                        $order_list[$ko]['create_time'] = $vo['create_time']; //订单生成时间
                        $order_list[$ko]['collection_no'] = $collectionInfo['collection_no'];
                    }
                } else {
                    $order_list[$ko]['scene_name'] = $vo['name'];
                    $order_list[$ko]['is_timing_order'] = $vo['is_timing_order'];
                    $order_list[$ko]['est_elapsed_time'] = ($vo['est_elapsed_time'] / 60) . '分钟';
                    $order_list[$ko]['bidding_start_time'] = date("Y年m月d日 H:i", strtotime($vo['bidding_start_time']));
                    if ($vo['bidding_end_time'] == '0000-00-00 00:00:00') {
                        $bidding_end_time = '竞拍未结束';
                    } else {
                        $bidding_end_time = date("Y年m月d日 H:i", strtotime($vo['bidding_end_time']));
                    }
                    $order_list[$ko]['bidding_end_time'] = $bidding_end_time;
                    $order_list[$ko]['bid_start_price'] = format_money($vo['bid_start_price']) . '元';
                    $order_list[$ko]['coupon'] = $vo['coupon'] . '元';
                    $order_list[$ko]['reserve_price'] = format_money($vo['reserve_price']) . '元';
                    $order_list[$ko]['show_reserve_price'] = $vo['show_reserve_price'];
                    $order_list[$ko]['commision'] = $vo['commision'] . '元';
                    $order_list[$ko]['transfer_fee'] =  $vo['transfer_type']==1 ? "--" : $vo['transfer_fee'] . '元'; //车商自过不收手续费
                    if ($vo['bidding_best_price'] > $vo['bid_best_price']) {
                        $best_price = $vo['bidding_best_price'];
                    } else {
                        $best_price = $vo['bid_best_price'];
                    }
                    $order_list[$ko]['bidding_best_price'] = format_money($best_price) . '元';
                }
            }
            /**
             * 车辆跟踪日志
             */
            $car_action_log = Car::get_car_trace_log_list($car_id);
            $this->assign('owner', $owner);
            $this->assign("car_info", $car_info);
            $this->assign('order_list', $order_list);
            $this->assign('car_action_log', $car_action_log);
        } else {
            $this->helpJsonResult(400, '没有此车辆！');
        }
        $c = new Car($car_id);
        $carInfo = $c->detail();
        $carIds = $c->getCarIdsBySid($carInfo['sid']);
        $count = count($carIds);
        $show_from = $this->get_from();  //获取渠道来源信息
        $this->assign('total_car', $count);
        $this->assign('car_id_list', $carIds);
        $this->assign('show_from', $show_from);
        $this->display();
    }

    /**
     *
     */

    /**
     * 按某键值排序
     * @param type $array
     * @param type $key
     * @param type $order
     * @return type
     */
    private function key_arr_sort($array, $key, $order = 'desc')
    {
        $arr_nums = $arr = array();
        foreach ($array as $k => $v) {
            $arr_nums[$k] = $v[$key];
        }
        if ($order == 'desc') {
            arsort($arr_nums);
        } else {
            asort($arr_nums);
        }
        foreach ($arr_nums as $k => $v) {
            $arr[$k] = $array[$k];
        }
        return $arr;
    }

    /**
     * 获取渠道来源信息
     */
    private function get_from()
    {
        $from = M("come_from a")->field("a.from_id,a.from_name,b.from_name AS pname,b.from_id AS pid,b.sort AS psort")
            ->join('(SELECT from_id,from_name,sort FROM au_come_from WHERE pid=-2 AND is_delete=0) AS b ON a.pid=b.from_id')
            ->where("a.pid!=-2 AND a.is_delete=0")
            ->order("psort ASC,pid DESC")
            ->select();
        $show_from = array();
        foreach ($from as $key => $val) {
            $show_from[$val['from_id']] = $val['pname'] . '-' . $val['from_name'];
        }
        return $show_from;
    }

}
